package pers.qianyu.listener;

import lombok.extern.slf4j.*;
import org.apache.rocketmq.spring.annotation.*;
import org.apache.rocketmq.spring.core.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.messaging.*;
import pers.qianyu.dao.*;
import pers.qianyu.domain.*;
import pers.qianyu.service.impl.*;

import java.util.*;

@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-topic-group")
public class OrderServiceImpl2Listener implements RocketMQLocalTransactionListener {
    @Autowired
    private TxLogDao txLogDao;
    @Autowired
    private OrderServiceImpl2 orderServiceImpl2;

    /**
     * 执行本地事务
     *
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            String txId = (String) message.getHeaders().get("txId");
            Order order = (Order) o;
            orderServiceImpl2.createOrder(txId, order);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 消息回查
     *
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("执行了消息回查，message：{}", message.toString());
        String txId = (String) message.getHeaders().get("txId");
        Optional<TxLog> op = txLogDao.findById(txId);
        if (op.isPresent()) {
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
